package com.linhngua.code.xml;

import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.util.Properties;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class XmlTransformer {
	
	public static final String	XALAN_INDENT_AMOUNT	= "{http://xml.apache.org/xslt}indent-amount";
	
	PrintErrorListener			errorListener;
	
	String						stylesheetFile;
	
	Logger						LOG					= LoggerFactory.getLogger(XmlTransformer.class);
	
	public XmlTransformer(String stylesheetFile,
			PrintErrorListener errorListener) {

		errorListener = new PrintErrorListener();
		this.stylesheetFile = stylesheetFile;
		this.errorListener = errorListener;
	}
	
	public String getStylesheetFile() {

		return stylesheetFile;
	}
	
	public void setStylesheetFile(String stylesheetFile) {

		this.stylesheetFile = stylesheetFile;
	}
	
	public String transform(String inXml) {

		String stylesheetID = stylesheetFile;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		// Create the transformer factory
		TransformerFactory factory = TransformerFactory.newInstance();
		
		// Set the error listener of the factory
		factory.setErrorListener(errorListener);
		
		// Create the transformer object
		try {
			Transformer transformer = factory.newTransformer(new StreamSource(
					stylesheetID));
			
			// Set the error listener of the transformer
			transformer.setErrorListener(errorListener);
			
			// Configure the transformer
			Properties props = new Properties();
			// props.put(OutputKeys.METHOD, "xml");
			// props.put(OutputKeys.INDENT, "yes");
			// props.put(XALAN_INDENT_AMOUNT, "2");
			props.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
			transformer.setOutputProperties(props);
			
			StreamResult result = new StreamResult(out);
			// Apply the transformation
			transformer.transform(new StreamSource(new StringReader(inXml)),
					result);
		}
		catch (Exception ex) {
			LOG.error("FAIL to transfrom xml message", ex);
			
		}
		return out.toString();
		
	}
	
}
